package lvjia.site.ai;

import okhttp3.*;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import static lvjia.site.ai.ver.upurl;
import java.util.Objects;

public class PlayerJoinListener implements Listener {
    private static final Logger LOGGER = LoggerFactory.getLogger(PlayerJoinListener.class);
    private FileConfiguration customConfig;
    private String modelname;
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Ai ai = (Ai) Bukkit.getPluginManager().getPlugin("ai");
        customConfig = new YamlConfiguration();
        try {
            customConfig.load(ai.customConfigFile);
        } catch (IOException | InvalidConfigurationException e) {
            e.printStackTrace();
        }
        Player player = event.getPlayer();
        String model = customConfig.getString("model");
        if (model != null) {
            modelname = Ai.getModelName(model);
        }
        customConfig = new YamlConfiguration();
        player.sendMessage("AI：我是"+modelname+"，可以帮你解答minecraft问题！我在后续会进行更多更新！使用/ai:ai [对话内容]与我对话！暂不支持连续对话。");



        if (player.isOp()){
            final OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(upurl)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String responseData = response.body().string();
                        double serverVer = Double.parseDouble(responseData);

                        if (ver.ver == serverVer) {
                            LOGGER.info("AI对话当前为最新版");
                            player.sendMessage("AI对话当前为最新版");
                        } else {
                            LOGGER.info("AI对话有新版本！在https://file.mingpixel.site 查看，当前版本为" + ver.ver + ",最新版为" + serverVer);
                            player.sendMessage("AI对话有新版本！在https://file.mingpixel.site 查看，当前版本为" + ver.ver + ",最新版为" + serverVer);
                        }
                    } else {
                        Bukkit.broadcastMessage("AI对话检查更新失败");
                        player.sendMessage("AI对话检查更新失败");
                    }
                }
            });
        }
    }
}
